#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class CharArray
{
public:
    CharArray(const char * pstr)
    : _capacity(strlen(pstr) + 1)
    , _data(new char[_capacity]())
    {
        strcpy(_data,pstr);
    }

    ~CharArray(){
        if(_data){
            delete [] _data;
            _data = nullptr;
        }
    }

    char & operator[](size_t idx){
        /* cout << "非const版本的operator[]被调用" << endl; */
        if(idx < _capacity - 1){
            return _data[idx];
        }else{
            cout << "out of range!" << endl;
            static char nullchar = '\0';
            return nullchar;
        }
    }

    //const成员函数限制了在函数体内修改数据成员
    //不能修改_capacity的值
    //不能修改_data记录的地址
    const char & operator[](size_t idx) const{
        /* cout << "const版本的operator[]被调用" << endl; */
        if(idx < _capacity - 1){
            /* _capacity = 100; */
            /* _data = new char[10](); */

            //这种写操作要人为避免
            /* _data[idx] = 'X'; */
            return _data[idx];
        }else{
            cout << "out of range!" << endl;
            static char nullchar = '\0';
            return nullchar;
        }
    }

private:
    size_t _capacity;
    char * _data;
};


void test0(){
    /* char arr[6] = {'h','e','l','l','o','\0'}; */
    /* char arr2[6] = "world"; */
    char arr3[] = "world";
    cout << arr3[0] << endl;
    arr3[0] = 'W';
    cout << arr3[0] << endl;


    CharArray ca("hello");
    /* ca.operator[](0); */
    cout << ca[0] << endl;
    ca[0] = 'H';
    cout << ca[0] << endl;

    const CharArray cb("world");
    /* cb.operator[](0); */
    /* cb[0] = 'A'; */
    cout << cb[0] << endl;
}

int main(void){
    test0();
    return 0;
}

